package com.lagou.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileOutAndInput {

    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("file1.txt");
        FileChannel channel = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("file2.txt");
        FileChannel outputStreamChannel = fileOutputStream.getChannel();

        // 方案一， 用 ByteBuffer 手动复制
//        ByteBuffer allocate = ByteBuffer.allocate(512);
//        while (true) {
//            allocate.clear();
//            int read = channel.read(allocate);
//            if (read == -1) {
//                break;
//            }
//            allocate.flip();
//            outputStreamChannel.write(allocate);
//        }

        // 方案2， 用内部方法
        outputStreamChannel.transferFrom(channel, 0, channel.size());

        outputStreamChannel.close();
        channel.close();
        fileInputStream.close();
        fileInputStream.close();
    }
}
